#include "gtrack_queue.h"

void initializeQueue(Queue* q, uint16_t capacity)
{
	q->front = -1;
	q->rear = -1;
    q->capacity = capacity;
    q->size = 0;
    q->items = (uint16_t*)gtrack_alloc(capacity, sizeof(uint16_t));
}

void freeQueue(Queue* q)
{
    q->front = -1;
    q->rear = -1;
    q->size = 0;
    if (q->items)
    {
        gtrack_free(q->items, q->capacity);
    }
    
    q->items = NULL;
    q->capacity = 0;
}

void resetQueue(Queue* q)
{
    q->front = -1;
    q->rear = -1;
    q->size = 0;
}

bool isEmpty(Queue* q)
{
	return q->front == -1;
}

bool isFull(Queue* q)
{
	return q->rear == q->capacity - 1;
}

void enqueue(Queue* q, int value)
{
    if (isFull(q)) {
        printf("Queue is full! Cannot enqueue %d\n", value);
        return;
    }
    if (isEmpty(q)) {
        q->front = 0;  // 如果队列为空，初始化队头指针
    }
    q->rear++;
    q->items[q->rear] = value;
    q->size++;
}

int dequeue(Queue* q)
{
    if (isEmpty(q)) {
        printf("Queue is empty! Cannot dequeue.\n");
        return -1;  // 返回一个无效值表示队列为空
    }
    int value = q->items[q->front];
    if (q->front == q->rear) {
        // 如果队列中只有一个元素，出队后重置队列
        q->front = -1;
        q->rear = -1;
        q->size = 0;
    }
    else {
        q->front++;
        q->size--;
    }
    return value;
}

int peek(Queue* q)
{
    if (isEmpty(q)) {
        printf("Queue is empty! No element to peek.\n");
        return -1;  // 返回一个无效值表示队列为空
    }
    return q->items[q->front];
}

void printQueue(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue is empty!\n");
        return;
    }
    printf("Queue elements: ");
    for (int i = q->front; i <= q->rear; i++) {
        printf("%d ", q->items[i]);
    }
    printf("\n");
}

